package org.example.groupwarehouse.controller;

import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.apache.ibatis.annotations.Param;
import org.example.groupwarehouse.entity.Admin;
import org.example.groupwarehouse.entity.Category;
import org.example.groupwarehouse.entity.Users;
import org.example.groupwarehouse.service.CategoryService;
import org.example.groupwarehouse.service.UserService;
import org.example.groupwarehouse.service.admin.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 * 处理管理员相关功能
 */
@Controller
@Validated
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService;

    // 管理员首页
    //登录退出功能
    @GetMapping("")
    public String admin(HttpSession session){
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser instanceof Admin)
        {
            return "admin";
        }
        return "redirect:/";
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("loginUser");
        session.removeAttribute("isAdmin");
        return "redirect:/user/login";
    }

    //增加商品
    @GetMapping("/goods/add")
    public String goodsAddPage(HttpSession session, Model model) {
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser instanceof Admin){
            // 获取所有类别数据
            List<Category> categories = categoryService.getAllCategories();
            model.addAttribute("categories", categories);
            return "goods_add";
        }
        return "login";
    }
    // 用户列表
    @GetMapping("/list")
    public String adminList(Model model) {
        List<Admin> adminList = adminService.getAllAdmins();
        model.addAttribute("adminList", adminList);
        return "admin_list";
    }

    // 添加管理员
    @PostMapping("/add")
    public String addAdmin(Admin admin) {
        // 验证账号长度(2-10位)
        if (admin.getAccount().length() < 2 || admin.getAccount().length() > 10) {
            return "redirect:/admin/list?error=account_length";
        }
        // 密码加密等处理在service层完成
        adminService.addAdmin(admin);
        return "redirect:/admin/list";
    }

    // 修改管理员状态(逻辑删除)
    @GetMapping("/delete/{id}")
    public String deleteAdmin(@PathVariable Integer id) {
        adminService.updateAdminStatus(id, 0); // 0表示已删除
        return "redirect:/admin/list";
    }

    // 修改密码
    @PostMapping("/changePassword")
    public String changePassword(Integer id, String newPassword) {
        adminService.changePassword(id, newPassword);
        return "redirect:/admin/list";
    }

    // 用户管理列表
    @GetMapping("/user/list")
    public String userList(HttpSession session, Model model,
                            @RequestParam(value = "account",required = false) String account,
                           @RequestParam(value = "eml" ,required = false) String eml,
                           @RequestParam(value = "tel",required = false) String tel) {


        System.out.println("model ------ > "+ account);
        Object loginUser = session.getAttribute("loginUser");
        if(!(loginUser instanceof Admin))
        {
            return "login";
        }
        //获取所有的用户数据
        List<Users> userlist = adminService.searchUsers(account,eml,tel);
        System.out.println("userlist " + userlist);
        model.addAttribute("userlist", userlist);
        return "admin_list";
    }


    //针对普通用户的操作
    //冻结
    @GetMapping("/user/freeze")
    public String freeze(@RequestParam Integer id, HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null || !(loginUser instanceof Admin)){
            return "login";
        }
        //冻结用户
        userService.freeze(id);
        return "redirect:/admin/user/list";
    }
    //解冻
    @GetMapping("/user/unfreeze")
    public String unfreeze(@RequestParam Integer id, HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null || !(loginUser instanceof Admin)){
            return "login";
        }
        //冻结用户
        userService.unfreeze(id);
        return "redirect:/admin/user/list";
    }
    //加入黑名单
    @GetMapping("user/blacklist/add")
    public String blacklistadd(@RequestParam Integer id, HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null || !(loginUser instanceof Admin)){
            return "login";
        }
        //加入黑名单用户
        userService.blacklist(id);
        return "redirect:/admin/user/list";
    }
    //解除黑名单
    @GetMapping("user/blacklist/remove")
    public String blacklistremove(@RequestParam Integer id, HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null || !(loginUser instanceof Admin)){
            return "login";
        }
        //加入黑名单用户
        userService.unblacklist(id);
        return "redirect:/admin/user/list";
    }
    //删除
    @GetMapping("user/delete")
    public String deleteUser(@RequestParam Integer id, HttpSession session) {
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null || !(loginUser instanceof Admin)){
            return "login";
        }
        //删除用户
        userService.delete(id);
        return "redirect:/admin/user/list";
    }

    @GetMapping("/checkAccount")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> checkAccount(
            @RequestParam @NotBlank @Size(min = 2, max = 10) String account,
            @RequestParam(required = false) Integer excludeId,
            HttpSession session) {

        // 1. 权限校验
        Object loginUser = session.getAttribute("loginUser");
        if (!(loginUser instanceof Admin)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("success", false, "message", "未登录或权限不足"));
        }

        // 2. 业务逻辑
        try {
            boolean exists = adminService.isAccountExist(account, excludeId);
            return ResponseEntity.ok(Map.of("exists", exists));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "服务器内部错误"));
        }
    }

    @PostMapping("/batchDelete")
    public String batchDeleteAdmins(@RequestParam("adminIds") List<Integer> adminIds,
                                    HttpSession session,
                                    RedirectAttributes redirectAttributes) {


        for(Integer id : adminIds){
            adminService.batchDelete(id);
        }

        return "redirect:/admin/user/list";

    }
}
